#!/bin/bash --login

#PBS -N C2m
#PBS -l select=2
#PBS -l walltime=12:00:00
#PBS -A e05-gener-wal
#PBS -q long

#Note: select = No. Nodes (e.g. 12 = 12*24 = 288 cores)

export OMP_NUM_THREADS=1
ulimit -s unlimited
module load vasp5/5.3.3

export NPROC=`qstat -f $PBS_JOBID | awk '/Resource_List.mpiprocs/ {print $3}'`

cd $PBS_O_WORKDIR

for dir in *
      do
    	pushd $dir
        cp ../INCAR* .
	cp ../standard_settings .
	cp *POSCAR* POSCAR
	finished_ions=`grep equired OUTCAR.Ions.Tight | awk '{print $1}'`
	finished_latt=`grep equired OUTCAR.Ions.Tight | awk '{print $1}'`
	finished_totl=`grep equired OUTCAR.Ions.Tight | awk '{print $1}'`       # reached if done

	if [ "$finished_ions" == 'reached' ]
    	then
    	echo "Ions optimisation already done, skipping to lattice"
	else
	cat standard_settings > INCAR
    	cat INCAR.Ions >> INCAR
	awk -f ../kpointer.awk POSCAR > KPOINTS
        aprun -n $NPROC /home/e05/shared/red/vasp5 > vasp.out 
    	cp OUTCAR OUTCAR.Ions
    	cp CONTCAR CONTCAR.Ions
    	cp CONTCAR POSCAR
	fi

	if [ "$finished_latt" == 'reached' ]
    	then
    	echo "Lattice optimisation already done, skipping to lattice"
	else
	cat standard_settings > INCAR
    	cat INCAR.Lattice >> INCAR
	awk -f ../kpointer.awk POSCAR > KPOINTS
        aprun -n $NPROC /home/e05/shared/red/vasp5 > vasp.out 
    	cp OUTCAR OUTCAR.Lattice
    	cp CONTCAR CONTCAR.Lattice
    	cp CONTCAR POSCAR
	fi
	
	if [ "$finished_totl" == 'reached' ]
    	then
    	echo "All optimisation done already!"
	else
	cat standard_settings > INCAR
    	cat INCAR.Ions.Tight >> INCAR
	awk -f ../kpointer.awk POSCAR > KPOINTS
        aprun -n $NPROC /home/e05/shared/red/vasp5 > vasp.out 
    	cp OUTCAR OUTCAR.Ions.Tight
    	cp CONTCAR CONTCAR.Ions.Tight
    	cp CONTCAR POSCAR
	fi
      popd
    done
